package cn.sfa.common.taglib;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sfa.common.utils.CommonUtil;
import cn.sfa.entity.users.SaleUsersLogin;

/**
 * 
* 类名称：HeaderTag   
* 类描述：jsp页面的头部信息自定义标签类
* 创建人：lenovo   
* 创建时间：2012-2-9 上午10:23:00     
* 修改备注：  
* @version  v1.0
 */
public class IndexHeaderTagBak  extends TagSupport{
	 


	/**
	 * 
	 */
	private static final long serialVersionUID = 1355396206595036725L;


	Logger logger = LoggerFactory.getLogger(IndexHeaderTagBak.class);


	String menuId;
	
	@Override
	public int doEndTag() throws JspException {

		return super.doEndTag();
	}

	@Override
	public int doStartTag() throws JspException {
		
		logger.info("--------------startTag--------------");
		
		String path = (String) pageContext.getRequest().getAttribute("path");
		
		String curURL = (String) pageContext.getRequest().getAttribute("curPath");
		
		SaleUsersLogin user = (SaleUsersLogin) pageContext.getSession().getAttribute("user");
		
		String userType = null;
		try {
			userType = user.getUserType();
			if ("USERTYPE_1".equals(userType)) {
				userType = "o1";
			} else if ("USERTYPE_2".equals(userType)) {
				userType = "o1";
			} else if ("USERTYPE_4".equals(userType)) {
				userType = "i1";
			} else if ("USERTYPE_3".equals(userType)) {
				userType = "i1";
			}
			logger.info("当前用户的类型:" + userType);
		} catch (Exception e) {
			
			HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
			HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
				try {
					response.sendRedirect(request.getContextPath()+"/sfa/sfa/index.jsp");//重定向登录页面
				} catch (IOException e1) {
					e1.printStackTrace();
				} 
		}
		String navURL="";
		String menuURL= "";
		//logger.info("===curURL=="+curURL);
		//navURL = "/"+curURL.split("/sfa/")[1];//导航菜单链接
		//navURL ="/"+navURL.split("/")[1]+"/index";
		//String menuURL= curURL.split("/sfa/")[1];//左菜单链接
		navURL="/"+curURL.split("/")[1]+"/index";
		menuURL= curURL.substring(1, curURL.length());
		if("login".equals(curURL.split("/")[2])){//登录的时候进行菜单初始化
			navURL="/news/index";
		}
		
		StringBuffer buffer = new StringBuffer();
		
		String dir = HeaderTag.class.getResource("/").getPath();
		dir = dir.replace("%20", " ");//对空格进行转义(否则无法识别路径)
		
		String cpath = dir+"menuxml//MenuConfig.xml";
		File f = new File(cpath);

		SAXReader reader = new SAXReader();
		Document document;
		try {
			document = reader.read(f);
		
		//获取根元素
		Element root = document.getRootElement();
	
		//获取导航菜单
		Element navMenu = (Element) root.selectSingleNode("//Navigation[@Url='"+navURL+"']");
		
		logger.info("navMenu="+navMenu);
		
		//获取当前菜单
		//当前菜单存在三种情况:1.当前菜单为主菜单链接;2.当前菜单为左菜单链接;3.当前菜单不在MenuConfig.xml文件中
		Element currentMenu = (Element) root.selectSingleNode("//Columns/Column[@Url='"+menuURL+"']");
		
		if(CommonUtil.isEmpty(currentMenu)){
			//currentMenu=navMenu.element("Group").element("Columns").element("Column");
			
		}else if(navURL.equals("/"+menuURL)){
			//currentMenu=navMenu.element("Group").element("Columns").element("Column");//TODO:如果为空,设置为第一个菜单项
		}
		
		logger.info("currentMenu="+currentMenu); 

		//获取所有的导航菜单
		List navList = root.selectNodes("Navigation"); 

		
		buffer.append("    <div class=\"top-header\">");
		buffer.append("        <div class=\"userinfo\">");
		buffer.append("            <img src=\"../statics/images/icon-user.gif\" style=\"margin-bottom: -6px; margin-right: 4px;\" /><span");
		buffer.append("                id=\"username\">"+user.getUserName()+"("+user.getLoginName()+")</span>，您好！<span style='margin-right:20px;'>&nbsp;上次登录时间:"+user.getLastLoginTime()+"</span><a href=\""+path+"/login/index/logout\">注销</a>");
		buffer.append("        </div>");
		buffer.append("    </div>");
		buffer.append("    <div class=\"container\">");
		buffer.append("        <!----------- 页面头部 ------------------>");
		buffer.append("        <div class=\"header\">");
		buffer.append("           <h1>");
		buffer.append("               <span>CRM客户关系管理系统</span>");
		buffer.append("            </h1>");
		buffer.append("            <!-----------  网站导航 ------------------>");
		buffer.append("            <ul class=\"navigation\" id=\"navigation\">");
		
		
		String navLevel="";
		int index = 0;
		int endIndex = navList.size();
		
		for(Iterator<Element> iter=navList.iterator();iter.hasNext(); ){
			Element  navElement = iter.next();
			
			navLevel = navElement.attributeValue("level");
			
			if(Arrays.asList(navLevel.split(",")).contains(userType)){
				
				if(index==0){
					buffer.append("<li class=\"navli-l\">");
				}else if(index ==endIndex){
					buffer.append("<li class=\"bgnone navli-r\">");
				}else{
					buffer.append("<li class=\"navli-m\">");
				}
				
				if(navMenu.attributeValue("Id").equals(navElement.attributeValue("Id"))){ 
					//buffer.append("<li class='nownav'><a href='"+path+navElement.attributeValue("Url")+"'><span>"+navElement.attributeValue("Name")+"</span></a>");
					buffer.append("<a href=\""+path+navElement.attributeValue("Url")+"\" class=\"current\"><span>"+navElement.attributeValue("Name")+"</span></a>");
				}else{
					//buffer.append("<li><a href='"+path+navElement.attributeValue("Url")+"'><span>"+navElement.attributeValue("Name")+"</span></a>");
					buffer.append("<a href=\""+path+navElement.attributeValue("Url")+"\" ><span>"+navElement.attributeValue("Name")+"</span></a>");
				}
				buffer.append("</li>");
				
			}
			index++;
		} 
		buffer.append("            </ul>");
		buffer.append("            <div style=\"clear: both\">");
		buffer.append("            </div>");
		buffer.append("        </div>");

		buffer.append("   <!----------- 页面内容 ------------------>");
		buffer.append("    <div class=\"content\" id=\"content\">"); 
		
		
		JspWriter out = pageContext.getOut();
		 try {
			out.println(buffer);//输出到jsp页面
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
		} catch (DocumentException e1) {
			
			e1.printStackTrace();
		}
		
		
		return super.doStartTag();
	}

}
